package com.lgw.coupon.controller;

import com.lgw.commons.model.domain.ResultInfo;
import com.lgw.commons.model.pojo.SeckillVouchers;
import com.lgw.commons.utils.ResultInfoUtil;
import com.lgw.coupon.annotation.RateLimiter;
import com.lgw.coupon.service.ISeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class SeckillController {
    @Autowired
    public ISeckillService seckillService;
    @Autowired
    public HttpServletRequest request;

    private static final String MESSAGE = "{\"code\":\"400\",\"msg\":\"FAIL\",\"desc\":\"触发限流\"}";

    @PostMapping("add")
    public ResultInfo addSeckillVouchers(@RequestBody SeckillVouchers seckillVouchers) {
        seckillService.addSeckillVouchers(seckillVouchers);
        return ResultInfoUtil.buildSuccess(request.getServletPath(), "添加成功");
    }

    @PostMapping("{voucherId}")
    @RateLimiter(limit = 100, expire = 2, message = MESSAGE)
    public ResultInfo daSeckill(@PathVariable Integer voucherId, String access_token) {
        log.info("进入秒杀controller");
        ResultInfo resultInfo = seckillService.doSeckill(voucherId, access_token, request.getServletPath());
        return resultInfo;
    }
}
